package com.qsj.easydarwin.service.impl;

import com.qsj.easydarwin.config.Config;
import com.qsj.easydarwin.controller.StreamController;
import com.qsj.easydarwin.pojo.FileListResponse;
import com.qsj.easydarwin.service.FileService;
import com.qsj.easydarwin.util.FfmpegUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Q1sj
 * @version 1.0
 * @date 2020/7/16 17:31
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private Config config;
    @Autowired
    private StreamController streamController;

    @Override
    public List<FileListResponse> getFileList(String videoPath) {
        // 遍历 目录下指定后缀文件
        Collection<File> videoList = FileUtils.listFiles(new File(videoPath), new String[]{"mp4", "avi"}, true);

        List<FileListResponse> responseList = new ArrayList<>();
        int length = config.getVideoPath().length();
        for (File file : videoList) {
            FileListResponse fileListResponse = new FileListResponse();
            // 格式化文件路径
            String filePath = file.getAbsolutePath().replaceAll("\\\\", "/");
            String substring = filePath.substring(length - 1);

            fileListResponse.setName(file.getName());
            fileListResponse.setPath(filePath);
            fileListResponse.setUrl(this.config.getDomain()+"video"+substring);
            // 判断是否在直播
            String rtsp ="";
            // 根据key(/服务区/服务区.mp4)获取
            FfmpegUtils ffmpegUtils = this.streamController.liveMap.get(filePath.substring(this.config.getVideoPath().length()-1));
            if (ffmpegUtils != null && !ffmpegUtils.isExit()) {
                rtsp = this.config.getRtspPath() + filePath.substring(config.getVideoPath().length()-1);
            }
            fileListResponse.setRtsp(rtsp);
            responseList.add(fileListResponse);
        }
        return responseList;
    }


    @Override
    public List<FileListResponse> getDirList() {
        File[] files = new File(this.config.getVideoPath()).listFiles();
        List<FileListResponse> responseList = new ArrayList<>();
        for (File file : files) {
            if (file.isDirectory()) {
                responseList.add(new FileListResponse(file.getName(), file.getAbsolutePath(), "", "",false));
            }
        }
        return responseList;
    }

    @Override
    public String saveCurrentImage(String videoUrl, Long time) {
        // 保存到本地
        String fileName = new FfmpegUtils().saveCurrentImage(videoUrl, time, this.config.getImagePath());
        // 返回 图片uri
        return "/image/"+fileName;
    }
}
